package com.ebor.utils.utils;

import com.ebor.utils.config.RequestBodyWrapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author C
 */
public class RequestUtils {

    public static JSONObject getHeaders(HttpServletRequest request) {
        JSONObject jo = new JSONObject();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            jo.put(key, value);
        }
        return jo;
    }

    public static Map<String,String> getFormData(HttpServletRequest request){
        Map<String,String> paramMap=new HashMap<>();
        Map<String,String[]> map= request.getParameterMap();
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            String[] vs = entry.getValue();
            if(Objects.isNull(vs)) {
                paramMap.put(entry.getKey(), "");
            } else if(vs.length == 1) {
                paramMap.put(entry.getKey(), entry.getValue()[0]);
            } else {
                paramMap.put(entry.getKey(), Arrays.toString(entry.getValue()));
            }
        }
        return paramMap;
    }

    public static String getParameter(HttpServletRequest request) {
        String param = "";
        if(StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), request.getMethod())) {
            if(StringUtils.equalsIgnoreCase("application/json", request.getContentType())) {
                RequestBodyWrapper wrapper = new RequestBodyWrapper(request);
                param = new String(wrapper.getRequestBody());
            }
            else if(request.getContentType().contains("multipart/form-data")){
                param = RequestUtils.getFormData(request).toString();
            }
        } else {
            param = request.getQueryString();
        }
        return param;
    }
}
